package cn.com.oceansoft.oauth.server.biz.dao.impl;

import cn.com.oceansoft.oauth.server.biz.dao.IOAuthClientsDao;
import cn.com.oceansoft.oauth.server.biz.entity.OAuthClients;
import cn.com.oceansoft.oauth.server.domain.shared.GuidGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by BEN on 2016/4/19.
 */
@Repository
public class OAuthClientsDaoImpl implements IOAuthClientsDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public OAuthClients findOAuthClients(String clientId) {

        final String sql = " select a.guid,a.client_id,a.client_secret,a.bound_ip,a.company,a.app_name,a.contacts,a.tel,a.create_time,b.archived " +
                "from oauth_clients a,oauth_client_details b where a.client_id=b.client_id and a.client_id = ?  order by create_time desc ";
        final List<OAuthClients> list = this.jdbcTemplate.query(sql, new Object[]{clientId}, BeanPropertyRowMapper.newInstance(OAuthClients.class));
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public List<OAuthClients> findAllOauthClients() {
        final String sql = " select a.guid,a.client_id,a.client_secret,a.bound_ip,a.company,a.app_name,a.contacts,a.tel,a.create_time,b.archived " +
                "from oauth_clients a,oauth_client_details b where a.client_id=b.client_id  order by create_time desc ";
        return this.jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(OAuthClients.class));
    }


    @Override
    public List<OAuthClients> findLikeOauthClients(String clientId) {
        final String sql = " select a.guid,a.client_id,a.client_secret,a.bound_ip,a.company,a.app_name,a.contacts,a.tel,a.create_time,b.archived " +
                "from oauth_clients a,oauth_client_details b where a.client_id=b.client_id and a.client_id like ?  order by create_time desc ";
        return this.jdbcTemplate.query(sql, new Object[]{clientId}, BeanPropertyRowMapper.newInstance(OAuthClients.class));
    }



    @Override
    public void updateOAuthClientsArchive(String clientId, boolean archive) {
        final String sql = " update oauth_client_details set archived = ? where client_id = ? ";
        this.jdbcTemplate.update(sql, archive, clientId);
    }

    @Override
    public void saveOAuthClients(OAuthClients clients) {
        final String sql = " insert into oauth_clients(guid,client_id,client_secret,bound_ip,company,app_name,contacts,tel,create_time) values (?,?,?,?,?,?,?,?,now()) ";
        this.jdbcTemplate.update(sql, GuidGenerator.generate(), clients.getClientId(), clients.getClientSecret(), clients.getBoundIp(), clients.getCompany(), clients.getAppName(), clients.getContacts(), clients.getTel());
    }
}
